import i18n from "@/lang";
import { dayjs, ElMessage } from "element-plus";

import {
  GenderEnum,
  IdCardTypeEnum,
  IdentityEnum,
  RechargeWayEnum,
  ReportStatusType,
  ReviewExplainEnum,
  UserStatusEnum,
} from "@/enum/baseEnum";

import {
  BalanceTypeEnum,
  PlatformTypeEnum,
  RechargeOrderStatusEnum,
  ReviewTypeEnum,
  TransactionTypeEnum,
  WithdrawTypeEnum,
} from "@/enum/financeEnum";

import { ProductUpStatusEnum } from "@/enum/productEnum";
import { useI18n } from "vue-i18n";
import { RechargeTagEnum } from "@/enum/diamondRechargeSettingEnum";
import { RenewalTypeEnum } from "@/enum/vipEnum";
// import useLanguageInfo from "@/hooks/useLanguageInfo";
// import type { LanguageRelationshipsType } from "@/type/languageInfoType";

const { t } = i18n.global;
// const { getLanguageInfoList } = useLanguageInfo();

export const getTableLabel = (tableName: string, row: any, prop: string) => {
  return row[prop];
};

export const testPhone = (phone: string) => {
  return /^\d{6,15}$/.test(phone);
  // return /^1[3456789]\d{9}$/.test(phone)
};

export const testMail = (mail: string) => {
  return /^([\w-\.]+)@([\w-\.]+)(\.[a-zA-Z0-9]+)$/.test(mail);
};

export const checkPhone = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("请输入电话号码"));
  } else if (!testPhone(value)) {
    return callback(new Error("请输入正确的电话号码"));
  }
  callback();
};

export const checkEmail = (rule: any, value: any, callback: any) => {
  if (!value) {
    if (rule.required) {
      return callback(new Error("请输入邮箱地址"));
    }
    return callback();
  } else if (!testMail(value)) {
    return callback(new Error("请输入正确的邮箱地址"));
  }
  callback();
};

export const filterTime = (time: string) => {
  return dayjs(time).format("YYYY-MM-DD HH:mm:ss");
};

export const getIdentityLabel = (userIdentityType: IdentityEnum) => {
  if (userIdentityType === IdentityEnum.NormalUser) {
    return t("NormalUser");
  } else if (userIdentityType === IdentityEnum.RealNameUser) {
    return t("AuthUser");
  } else if (userIdentityType === IdentityEnum.VipUser) {
    return t("VipUser");
  } else {
    return "--";
  }
};

export const setTableHeaderRowStyle = () => {
  return {
    height: "42px",
  };
};

export const setTableHeaderCellStyle = () => {
  return {
    height: "42px",
    backgroundColor: "#F2F3F5",
    color: "#2A2A2A",
    fontSize: "14px",
    fontWeight: "800",
  };
};

export const setTableRowStyle = () => {
  return {
    height: "42px",
  };
};

export const setTableCellStyle = ({
  row,
  rowIndex,
}: {
  row: any;
  rowIndex: number;
}) => {
  let style = {
    height: "42px",
    backgroundColor: "#fff",
    color: "#02011B",
  };
  if (rowIndex % 2 !== 0) {
    style.backgroundColor = "#F9F9FB";
  }
  return style;
};

export const setNoBorderTableCellStyle = ({
  row,
  rowIndex,
}: {
  row: any;
  rowIndex: number;
}) => {
  let style = {
    height: "42px",
    backgroundColor: "#fff",
    color: "#02011B",
  };
  return style;
};

export const getUpDownLabel = (status: ProductUpStatusEnum) => {
  if (status === ProductUpStatusEnum.Down) {
    return t("Listing");
  }
  return t("OffShelf");
};

export const getUserStatusLabel = (status: UserStatusEnum) => {
  switch (status) {
    case UserStatusEnum.Normal:
      return t("Normal");
    case UserStatusEnum.Disable:
      return t("AlDisabled");
    case UserStatusEnum.Delete:
      return t("AlDelete");
    case UserStatusEnum.Cancellation:
      return t("AlCancellation");
    default:
      return "--";
  }
};

export const getTableRechargeStatusLabel = (status: ProductUpStatusEnum) => {
  if (status === ProductUpStatusEnum.Up) {
    return t("Normal");
  }
  return t("OffShelf");
};

export const getGenderLabel = (gender: string) => {
  switch (gender) {
    case "F":
      return t("Female");
    case "M":
      return t("Man");
    default:
      return t("Other");
  }
};

export const getGenderLabelByEnum = (gender: GenderEnum) => {
  switch (gender) {
    case GenderEnum.Female:
      return t("Female");
    case GenderEnum.Male:
      return t("Man");
    default:
      return t("Other");
  }
};

export const getAuthTypeEnum = (authType: IdCardTypeEnum) => {
  switch (authType) {
    case IdCardTypeEnum.IdCard:
      return t("IdCard");
    default:
      return "--";
  }
};

export const filterSmallPhotoPath = (path: string) => {
  return `${path.substring(0, 11)}t_${path.substring(11)}`;
};

export const filterPhoneNum = (phone: string) => {
  if (!phone) return "";
  return phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
};

export const getReviewExplainLabel = (reviewExplain: ReviewExplainEnum) => {
  console.log(reviewExplain);

  switch (reviewExplain) {
    case ReviewExplainEnum.OrderApply_Wallet:
      return t("OrderApply_Num");
    case ReviewExplainEnum.OrderApply_Offline:
      return t("OrderApply_Offline");
    case ReviewExplainEnum.OrderApply_Withdrawal:
      return t("OrderApply_Withdrawal");
    case ReviewExplainEnum.OrderApply_ActivityReward:
      return t("OrderApply_ActivityReward");
    case ReviewExplainEnum.OrderApply_OfflineWithdrawal:
      return t("OrderApply_OfflineWithdrawal");
    case ReviewExplainEnum.OrderApply_OrderRisk:
      return t("OrderApply_OrderRisk");
    case ReviewExplainEnum.OrderAdjustment_ReCheck:
      return t("OrderAdjustment");
    case ReviewExplainEnum.OrderRefund:
      return t("RechargeRefund");
    default:
      return "--";
  }
};

export const disableDate = (date: Date) => {
  let time = dayjs(date);
  let nowDate = dayjs();
  let beforeHalfYear = dayjs().subtract(6, "month");
  return !(
    time.valueOf() > beforeHalfYear.valueOf() &&
    time.valueOf() < nowDate.valueOf()
  );
};

export const getReviewTypeLabel = (reviewType: ReviewTypeEnum) => {
  switch (reviewType) {
    case ReviewTypeEnum.ActivityRewardApply:
      return t("ActivityRewardApply");
    case ReviewTypeEnum.AmountAdjustmentApply:
      return t("AmountAdjustmentApply");
    case ReviewTypeEnum.DataCardApply:
      return t("DataCardApply");
    case ReviewTypeEnum.DataScheduleApply:
      return t("DataScheduleApply");
    case ReviewTypeEnum.OfflineWithdrawalApply:
      return t("OfflineWithdrawalApply");
    case ReviewTypeEnum.OrderRiskAudit:
      return t("OrderRiskAudit");
    case ReviewTypeEnum.OfflineRechargeApply:
      return t("OfflineRechargeApply");
    case ReviewTypeEnum.UserPhotoAudit:
      return t("UserPhotoAudit");
    case ReviewTypeEnum.WithdrawalApply:
      return t("WithdrawalApply");
    case ReviewTypeEnum.OrderAdjustment:
      return t("OrderAdjustment");
    case ReviewTypeEnum.OrderRefund:
      return t("RechargeRefund");
    default:
      return "--";
  }
};

export const getPlatformLabel = (platformType: PlatformTypeEnum) => {
  switch (platformType) {
    case PlatformTypeEnum.GooglePay:
      return "Google";
    case PlatformTypeEnum.IOS:
      return "IOS";
    case PlatformTypeEnum.Web:
      return "Stripe";
    case PlatformTypeEnum.Windows:
      return "Windows";
    case PlatformTypeEnum.Management:
      return t("OrderApply_Offline");
    default:
      return "--";
  }
};

export const getWithPlatformLabel = (withdrawType: WithdrawTypeEnum) => {
  switch (withdrawType) {
    case WithdrawTypeEnum.Online:
      return t("OnlineWith");
    case WithdrawTypeEnum.Outline:
      return t("OfflineWith");
    default:
      return "--";
  }
};

export const getRechargeLabel = (rechargeWay: RechargeWayEnum) => {
  switch (rechargeWay) {
    case RechargeWayEnum.Apple:
      return "IOS";
    case RechargeWayEnum.GooglePay:
      return "Google";
    case RechargeWayEnum.Stripe:
      return "Stripe";
    case RechargeWayEnum.OfflineRecharge:
      return t("OfflineRecharge");
    default:
      return "--";
  }
};

export const getRenewalTypeLabel = (renewalType: RenewalTypeEnum) => {
  switch (renewalType) {
    case RenewalTypeEnum.AutoRenewable:
      return t("AutoRenewable");
    case RenewalTypeEnum.Disposable:
      return t("Disposable");
    default:
      return "--";
  }
};

export const getRechargeOrderStatusLabel = (
  orderStatus: RechargeOrderStatusEnum
) => {
  switch (orderStatus) {
    case RechargeOrderStatusEnum.New:
      return t("NewOrder");
    case RechargeOrderStatusEnum.PaySuccess:
      return t("PaySuccess");
    case RechargeOrderStatusEnum.Cancel:
      return t("OrderCancel");
    case RechargeOrderStatusEnum.CheckedSuccess:
      return t("CheckedSuccess");
    case RechargeOrderStatusEnum.CheckedFailed:
      return t("CheckedFail");
    case RechargeOrderStatusEnum.OrderPending:
      return t("OrderPending");
    case RechargeOrderStatusEnum.IssueFail:
      return t("IssueFail");
    case RechargeOrderStatusEnum.OrderFailed:
      return t("OrderFailed");
    case RechargeOrderStatusEnum.Completed:
      return t("OrderSuccess");
    case RechargeOrderStatusEnum.CheckPending:
      return t("CheckPending");
    case RechargeOrderStatusEnum.LockOrder:
      return t("LockOrder");
    case RechargeOrderStatusEnum.Refund:
      return t("RefundSuccess");
    default:
      return "--";
  }
};

export const getWithOrderStatusLabel = (
  orderStatus: RechargeOrderStatusEnum
) => {
  switch (orderStatus) {
    case RechargeOrderStatusEnum.New:
      return t("NewOrder");
    case RechargeOrderStatusEnum.PaySuccess:
      return t("PaySuccess");
    case RechargeOrderStatusEnum.Cancel:
      return t("OrderCancel");
    case RechargeOrderStatusEnum.CheckedSuccess:
      return t("CheckedSuccess");
    case RechargeOrderStatusEnum.CheckedFailed:
      return t("CheckedFail");
    case RechargeOrderStatusEnum.OrderPending:
      return t("WaitAudit");
    case RechargeOrderStatusEnum.IssueFail:
      return t("IssueFail");
    case RechargeOrderStatusEnum.OrderFailed:
      return t("WithFail");
    case RechargeOrderStatusEnum.Completed:
      return t("WithSuccess");
    case RechargeOrderStatusEnum.CheckPending:
      return t("CheckPending");
    case RechargeOrderStatusEnum.LockOrder:
      return t("LockOrder");
    default:
      return "--";
  }
};

export const getRechargeTagLabel = (purchaseDiamondLabel: RechargeTagEnum) => {
  switch (purchaseDiamondLabel) {
    case RechargeTagEnum.QuickPay:
      return t("QuickPay");
    case RechargeTagEnum.NormalPay:
      return t("NormalPay");
    default:
      return "--";
  }
};

export const getReportStatusTypeLabel = (status: ReportStatusType) => {
  switch (status) {
    case ReportStatusType.Normal:
      return t("Normal");
    case ReportStatusType.Banning:
      return t("Banning");
    case ReportStatusType.Process:
      return t("Process");
    default:
      return "--";
  }
};

export const getUpDownStatusLabel = (status: ProductUpStatusEnum) => {
  switch (status) {
    case ProductUpStatusEnum.Up:
      return t("Listing");
    case ProductUpStatusEnum.Down:
      return t("OffShelf");
    default:
      return "--";
  }
};

export const getCurrencyLabel = (currencyCode: string) => {
  return currencyCode;
};

export const getI18nProductName = (row: any) => {
  const { locale } = useI18n();
  if (locale.value === "") {
    return row.cnName;
  } else if (locale.value === "za") {
    return row.traChName;
  } else {
    return row.usName;
  }
};

export const getPriceNum = (val: string) => {
  let value = val;
  if (val.length === 0) {
    return value;
  }
  if (val.length === 1) {
    value = value.replace(".", "");
    return value;
  }
  value = value
    .replace(/[^\d.]/g, "")
    .replace(/\.{2,}/g, ".")
    .replace(".", "$#$")
    .replace(/\./g, "")
    .replace("$#$", ".")
    .replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3");
  if (value.indexOf("0") === 0) {
    value = value.replace("0", "");
  }
  return value;
};

export const getTransactionTypeLabel = (
  transactionType: TransactionTypeEnum
) => {
  switch (transactionType) {
    case TransactionTypeEnum.Recharge:
      return t("Recharge");
    case TransactionTypeEnum.Exchange:
      return t("Exchange");
    case TransactionTypeEnum.Withdrawal:
      return t("Withdrawal");
    case TransactionTypeEnum.OfflineRecharge:
      return t("OfflineRecharge1");
    case TransactionTypeEnum.ActivityReward:
      return t("ActivityReward");
    case TransactionTypeEnum.AmountAdjustment:
      return t("AmountAdjustment");
    case TransactionTypeEnum.Refund:
      return t("RechargeRefund");
    case TransactionTypeEnum.GenerationRecharge:
      return t("GenerationRecharge");
    case TransactionTypeEnum.Settlement:
      return t("Settlement");
    case TransactionTypeEnum.VipRecharge:
      return t("VipRecharge");
    case TransactionTypeEnum.Gift:
      return t("Gift");
    case TransactionTypeEnum.Video:
      return t("Video");
    case TransactionTypeEnum.Voice:
      return t("Voice");
    case TransactionTypeEnum.Appointment:
      return t("Appointment");
    case TransactionTypeEnum.AvatarFrame:
      return t("AvatarFrame");
    case TransactionTypeEnum.OfflineCashWithdrawal:
      return t("OfflineCashWithdrawal");
    case TransactionTypeEnum.ConvertCode:
      return t("RedeemCode");
    default:
      return "--";
  }
};

export const getBalanceType = (balanceType: BalanceTypeEnum) => {
  switch (balanceType) {
    case BalanceTypeEnum.Diamond:
      return t("DiamondLabel");
    case BalanceTypeEnum.Gold:
      return t("GoldCoin");
    case BalanceTypeEnum.Cash:
      return t("Cash");
    default:
      return "--";
  }
};

export const compareMonth = (start: Date, end: Date, num: number) => {
  // 复制开始日期
  Date.prototype.clone = function () {
    return new Date(this.valueOf());
  };
  let date = new Date(start);
  let startNormal = date.clone();
  let startResult = date.clone();
  let start1 = date.clone();

  let rightDate;
  let isBelong = false;
  // 计算开始日期所在的日数
  let startDate = new Date(start1).getDate();
  // 推算num个月后的日期
  let endDate = new Date(start1.setMonth(start1.getMonth() + num, startDate));
  let endDateMonth = new Date(endDate).getMonth();
  // 如果num个月后的日期所在的月份跟开始日期所在月份相差大于了num，则应结束日期定位到上个月的最后一天
  let startToRightEndMonth =
    new Date(startNormal).getMonth() + num > 12
      ? new Date(startNormal).getMonth() + num - 12
      : new Date(startNormal).getMonth() + num;
  // 获取到应结束日期
  let shouldEndDate;
  if (endDateMonth > startToRightEndMonth) {
    shouldEndDate = new Date(
      startNormal.setMonth(startNormal.getMonth() + num + 1, 0)
    );
  } else {
    shouldEndDate = endDate;
  }
  // 比较结束日期是否小于应结束日期
  if (new Date(end).getTime() < new Date(shouldEndDate).getTime()) {
    rightDate = end;
    isBelong = true;
  } else {
    rightDate = shouldEndDate;
    isBelong = false;
  }
  return { startResult, rightDate, isBelong };
};
export const countValidator = (rule: any, value: any, callback: any) => {
  console.log(value);
  if (value == 0) {
    // ElMessage({
    //     type: "warning",
    //     message: t("EnterNoZero"),
    // });
    return callback(new Error(t("EnterNoZero")));
  }
  callback();
};
export const formatterValidator = (rule: any, value: any, callback: any) => {
  console.log(value);
  if (value && isNaN(value)) {
    // ElMessage({
    //     type: "warning",
    //     message: t("EnterNoZero"),
    // });
    return callback(new Error(t("FormatError")));
  }
  callback();
};

export const CheckNewPassWord = (rule: any, value: any, callback: any) => {
  var str = value;
  if (str == null || str.length < 6) {
    return callback(new Error(t("PasswordErrorMsg")));
  }
  var reg1 = new RegExp(/^[0-9A-Za-z]+$/);
  if (!reg1.test(str)) {
    return callback(new Error(t("PasswordErrorMsg")));
  }
  var reg = new RegExp(/[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/);
  if (reg.test(str)) {
    callback();
  } else {
    return callback(new Error(t("PasswordErrorMsg")));
  }
};
export const CheckConfirmPassWord = (rule: any, value: any, callback: any) => {
  var str = value;
  if (str == null || str.length < 6) {
    return callback(new Error(t("PasswordConfirmErrorMsg")));
  }
  var reg1 = new RegExp(/^[0-9A-Za-z]+$/);
  if (!reg1.test(str)) {
    return callback(new Error(t("PasswordConfirmErrorMsg")));
  }
  var reg = new RegExp(/[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/);
  if (reg.test(str)) {
    callback();
  } else {
    return callback(new Error(t("PasswordConfirmErrorMsg")));
  }
};
export const checkCustomTime = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error(t("PleaseChoose")));
  }
  if (value.length === 0) {
    return callback(new Error(t("PleaseChoose")));
  }
  let custom = dayjs(value[1]);
  let today = dayjs();
  if (custom.format("YYYY-MM-DD") === today.format("YYYY-MM-DD")) {
    return callback();
  } else {
    if (custom.valueOf() < today.valueOf()) {
      return callback(new Error(t("TheEndTimeNotLessThanCurrentTime")));
    } else {
      return callback();
    }
  }
};

export const moneyFormat = (
  num: number,
  currency: string = "USD",
  isFormat: boolean = true,
  isInt: boolean = false
) => {
  let s: any = num + "";
  s = s.replace(",", "");
  let pre = s.indexOf("-") > -1 ? "-" : "";
  s = s.replace("-", "");
  let num3: any = s;
  // 10亿以上转换为B
  if (isFormat && num3 >= 1000000000) {
    num3 = parseInt(String(num3 / 1000000000)) + "";
    let lastNum: any = Math.floor(s / 10000000) / 100 + "";
    let lastPre = "";
    if (
      lastNum.split(".").length == 2 &&
      lastNum.split(".")[1] !== "00" &&
      lastNum.split(".")[1] != 0
    ) {
      lastPre = `.${lastNum.split(".")[1]}`;
    }
    num3 = num3.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return pre + num3 + lastPre + "B";
  }
  // 1千万 以上转换M
  if (isFormat && num3 >= 10000000) {
    num3 = parseInt(String(num3 / 1000000)) + "";
    let lastNum: any = Math.floor(s / 10000) / 100 + "";
    let lastPre = "";
    if (
      lastNum.split(".").length == 2 &&
      lastNum.split(".")[1] !== "00" &&
      lastNum.split(".")[1] != 0
    ) {
      lastPre = `.${lastNum.split(".")[1]}`;
    }
    num3 = num3.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return pre + num3 + lastPre + "M";
  }
  // 1百万 以上转换M
  if (isFormat && num3 >= 1000000) {
    num3 = parseInt(String(num3 / 1000000)) + "";
    let lastNum: any = Math.floor(s / 10000) / 100 + "";
    let lastPre = "";
    if (
      lastNum.split(".").length == 2 &&
      lastNum.split(".")[1] !== "00" &&
      lastNum.split(".")[1] != 0
    ) {
      lastPre = `.${lastNum.split(".")[1]}`;
    }
    num3 = num3.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return pre + num3 + lastPre + "M";
  }
  // 10000 以上转换K
  if (isFormat && num3 >= 10000) {
    num3 = parseInt(String(num3 / 1000)) + "";
    let lastNum: any = Math.floor(s / 10) / 100 + "";
    let lastPre = "";
    if (
      lastNum.split(".").length == 2 &&
      lastNum.split(".")[1] !== "00" &&
      lastNum.split(".")[1] != 0
    ) {
      lastPre = `.${lastNum.split(".")[1]}`;
    }
    num3 = num3.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return pre + num3 + lastPre + "K";
  }
  // if (sessionStorage.getItem("$winbox") === "DDWIN") {
  //     num3 = digitFormat(num3);
  // } else {
  num3 = parseFloat(num3).toFixed(2);
  // }
  if (isInt || currency == "IDR" || currency == "VND") {
    // 整数处理
    num3 = num3.substring(0, num3.indexOf("."));
  }
  return pre + num3.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};
export const sortList = (
  languageRelationships: Array<LanguageRelationshipsType>
) => {
  const languageList = getLanguageInfoList();
  languageRelationships.map((item: LanguageRelationshipsType) => {
    let language = languageList.filter((itemA) => {
      return languageRelationships.every((itemB: LanguageRelationshipsType) => {
        return itemB.languageId !== itemA.id;
      });
    });
    let [normalList] = languageList.filter(
      (itemA) => item.languageId == itemA.id
    );
    if (normalList) language.unshift(normalList);
    item.languageList = language;
    if (!item.languageCode) {
      item.languageCode = normalList?.code;
    }
  });
};
export const timeFormater = (time: number): string => {
  let second = parseInt(time + "");
  let minute = 0;
  let hour = 0;
  if (second > 60) {
    minute = parseInt(second / 60 + "");
    second = parseInt((second % 60) + "");
    if (minute > 60) {
      hour = parseInt(minute / 60 + "");
      minute = parseInt((minute % 60) + "");
    }
  }
  return `${hour ? (hour > 9 ? hour : "0" + hour) : ""}${
    minute > 9 ? minute : "0" + minute
  }:${second > 9 ? second : "0" + second}`;
};
// html编码（转义）
export const htmlEncodeByRegExp = (str: string) => {
  var temp = "";
  if (str.length == 0) return "";
  temp = str.replace(/&/g, "&amp;");
  temp = temp.replace(/</g, "&lt;");
  temp = temp.replace(/>/g, "&gt;");
  temp = temp.replace(/\s/g, "&nbsp;");
  temp = temp.replace(/\'/g, "&#39;");
  temp = temp.replace(/\"/g, "&quot;");
  return temp;
};
// html解码（反转义）
export const htmlDecodeByRegExp = (str: string) => {
  var temp = "";
  if (str.length == 0) return "";
  temp = str.replace(/&amp;/g, "&");
  temp = temp.replace(/&lt;/g, "<");
  temp = temp.replace(/&gt;/g, ">");
  temp = temp.replace(/&nbsp;/g, " ");
  temp = temp.replace(/&#39;/g, "'");
  temp = temp.replace(/&quot;/g, '"');
  return temp;
};
// 回车\r\n转为标签
export const return2Br = (str: string) => {
  return str.replace(/\r?\n/g, "<br />");
};
// 判断字符串是否是html
export const isHTML = (str: string) => {
  var a = document.createElement("div");
  a.innerHTML = str;
  for (var c = a.childNodes, i = c.length; i--; ) {
    if (c[i].nodeType == 1) return true;
  }
  return false;
};
// 字符串转换
export const convertString = (str: string) => {
  const text = str;
  if (isHTML(text)) {
    return htmlEncodeByRegExp(text);
  } else {
    return htmlDecodeByRegExp(htmlEncodeByRegExp(return2Br(text)));
  }
};

export const formatSubmitInput = (val: any, max?: number) => {
  let value = val.replace(/[^1234567890.]/g, "");
  if (value === ".") {
    return "0.00";
  }
  let pointIndex = value.indexOf(".");
  let pointLastIndex = value.lastIndexOf(".");
  if (pointIndex !== -1) {
    if (pointIndex == pointLastIndex) {
      value = value.substring(0, pointIndex + 3);
    } else {
      value = value.substring(0, pointIndex + 1);
    }
  } else {
    let numVal = Number(val);
    if (!isNaN(numVal)) value = numVal;
  }
  if (max) {
    if (value > max) {
      value = max;
    }
  }
  return value;
};

export const getBankName = (item: BankCardListType) => {
  const { locale } = useI18n();
  if (locale.value === "zh") {
    return item.bankCnName;
  } else if (locale.value === "za") {
    return item.bankTraChName;
  } else {
    return item.bankUsName;
  }
};

export const filterBankNoLabel = (bankCardNo: string) => {
  if (!bankCardNo) return "";
  let length = bankCardNo.length;
  if (length > 7) {
    return `${bankCardNo.substring(0, 4)}****${bankCardNo.substring(
      length - 4
    )}`;
  } else if (length === 7) {
    return `${bankCardNo.substring(0, 3)}****${bankCardNo.substring(
      length - 4
    )}`;
  } else if (length === 6) {
    return `${bankCardNo.substring(0, 2)}****${bankCardNo.substring(
      length - 4
    )}`;
  } else {
    return `${bankCardNo.substring(0, 1)}****${bankCardNo.substring(
      length - 4
    )}`;
  }
};

export const formatTime = (time: any) => {
  return dayjs(time).format("YYYY-MM-DD");
};

// 判断日期区间是否再当月
export const isSameMonthAndYear = (dates: [string, string]): boolean => {
  const [startDate, endDate] = dates;
  const start = dayjs(startDate);
  const end = dayjs(endDate);

  if (start.year() === end.year() && start.month() === end.month()) {
    return true;
  } else {
    ElMessage.error(t("OrderDateErrorMessage"));
    return false;
  }
};
